package com.thirtydays.frame.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.fragment.app.Fragment
import coil.request.ImageRequest
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.PictureSelectionConfig.selectorStyle
import com.luck.picture.lib.engine.CropEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.utils.ActivityCompatHelper
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.StyleUtils
import com.thirtydays.frame.base.BaseApp
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import java.io.File


/**
 * @创建者：小垚
 * @时间：2022/2/25  18:07
 * @描述：
 */
class ImageCropEngine : CropEngine {

    override fun onStartCrop(
        fragment: Fragment,
        currentLocalMedia: LocalMedia,
        dataSource: ArrayList<LocalMedia>,
        requestCode: Int
    ) {
        val currentCropPath = currentLocalMedia.availablePath
        val inputUri = if (PictureMimeType.isContent(currentCropPath) || PictureMimeType.isHasHttp(currentCropPath)) {
            Uri.parse(currentCropPath)
        } else {
            Uri.fromFile(File(currentCropPath))
        }
        val fileName: String = DateUtils.getCreateFileName("CROP_").toString() + ".jpg"
        val destinationUri: Uri = Uri.fromFile(File(getSandboxPath(), fileName))
        val options: UCrop.Options = buildOptions()
        val dataCropSource = ArrayList<String>()
        dataSource.forEach {
            dataCropSource.add(it.availablePath)
        }
        val uCrop = UCrop.of(inputUri, destinationUri, dataCropSource)
        uCrop.withOptions(options)
        uCrop.setImageEngine(object : UCropImageEngine {
            override fun loadImage(context: Context, url: String, imageView: ImageView) {
                if (!ActivityCompatHelper.assertValidRequest(context)) {
                    return
                }

                ImageRequest.Builder(context)
                    .data(url)
                    .size(180, 180)
                    .target(imageView)
                    .build()

            }

            override fun loadImage(
                context: Context,
                url: Uri,
                maxWidth: Int,
                maxHeight: Int,
                call: UCropImageEngine.OnCallbackListener<Bitmap?>?
            ) {
                if (!ActivityCompatHelper.assertValidRequest(context)) {
                    return
                }
                ImageRequest.Builder(context)
                    .data(url)
                    .size(maxWidth, maxHeight)
                    .target {
                        call?.run {
                            onCall((it as BitmapDrawable).bitmap)
                        }
                    }
                    .build()
            }
        })
        uCrop.start(fragment.requireActivity(), fragment, requestCode)
    }

    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private fun getSandboxPath(): String {
        val externalFilesDir = BaseApp.appContent.getExternalFilesDir("")
        val customFile = File(externalFilesDir?.absolutePath, "Sandbox")
        if (!customFile.exists()) {
            customFile.mkdirs()
        }
        return customFile.absolutePath + File.separator
    }

    /**
     * 配制UCrop，可根据需求自我扩展
     *
     * @return
     */
    private fun buildOptions(): UCrop.Options {
        val options = UCrop.Options()
        options.setHideBottomControls(true)  //设置隐藏底部控件
        options.setFreeStyleCropEnabled(true) //设置自由样式裁剪启用
        options.setShowCropFrame(true) //设置显示裁剪框
        options.setShowCropGrid(true) //设置显示裁剪网格
        options.setCircleDimmedLayer(true) //设置圆形暗淡层
        options.withAspectRatio(1f, 1f) //设置纵横比
        options.setCropOutputPathDir(getSandboxPath()) //设置裁剪输出路径目录
        options.isCropDragSmoothToCenter(false) //是裁剪拖动平滑到中心
        options.isUseCustomLoaderBitmap(false) //是使用自定义加载器位图
        options.setSkipCropMimeType(PictureMimeType.ofGIF(), PictureMimeType.ofWEBP()) //设置跳过裁剪 Mime 类型
        options.isForbidCropGifWebp(true) //是禁止作物 Gif Webp
        options.isForbidSkipMultipleCrop(false) //是禁止跳过多重裁剪
        options.setMaxScaleMultiplier(100f) //设置最大比例乘数
        if (selectorStyle != null && selectorStyle.selectMainStyle.statusBarColor != 0) {
            val mainStyle = selectorStyle.selectMainStyle
            val isDarkStatusBarBlack = mainStyle.isDarkStatusBarBlack
            val statusBarColor = mainStyle.statusBarColor
            options.isDarkStatusBarBlack(isDarkStatusBarBlack)
            if (StyleUtils.checkStyleValidity(statusBarColor)) {
                options.setStatusBarColor(statusBarColor)
                options.setToolbarColor(statusBarColor)
            } else {
                options.setStatusBarColor(Color.parseColor("#EEEEEE"))
                options.setToolbarColor(Color.parseColor("#EEEEEE"))
            }
            val titleBarStyle = selectorStyle.titleBarStyle
            if (StyleUtils.checkStyleValidity(titleBarStyle.titleTextColor)) {
                options.setToolbarWidgetColor(titleBarStyle.titleTextColor)
            } else {
                options.setToolbarWidgetColor(Color.WHITE)
            }
        } else {
            options.setStatusBarColor(Color.parseColor("#EEEEEE"))
            options.setToolbarColor(Color.parseColor("#EEEEEE"))
            options.setToolbarWidgetColor(Color.WHITE)
        }
        return options
    }

}